<template>
  <div class="menu-management-container">
    <el-row :gutter="20">
      <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-tree
            :data="data"
            :default-expanded-keys="expandDefault"
            highlight-current
            node-key="id"
            :props="defaultProps"
            :render-content="renderContent"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>
      <el-col :lg="20" :md="16" :sm="24" :xl="20" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-button
                v-if="MenuAuth('add')"
                :icon="Plus"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
            </vab-query-form-top-panel>
          </vab-query-form>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            default-expand-all
            row-key="path"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column
              :label="translate('编码')"
              prop="Code"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('岗位')"
              prop="FullName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('所属公司')"
              prop="CompanyName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('所属部门')"
              prop="DepartmentName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('是否有效')"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.Enabled ? translate('是') : translate('否') }}
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('描述')"
              prop="Remark"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('操作')"
              show-overflow-tooltip
              width="240"
            >
              <template #default="{ row }">
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                  plain
                >
                  {{ translate('编辑') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>
    <edit ref="editRef" :tree="data" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getTree, getList } from '@/api/postManagement'
  import { Plus } from '@element-plus/icons-vue'
  import { useSettingsStore } from '@/store/modules/settings'
  import { MenuAuth } from '~/src/utils/permission'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'PostManagement',
    components: {
      Edit: defineAsyncComponent(() =>
        import('./components/PostManagementEdit')
      ),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        editRef: null,
        data: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        list: [],
        queryTreeForm: {
          companyId: '0',
          departmentId: 'string',
          nature: 'string',
        },
        queryForm: {
          pageNo: 1,
          pageSize: 20,
          total: 0,
          tableName: 'string',
          sort: 'SortCode',
          order: 'string',
          wheres: 'string',
          export: true,
          value: 'string',
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        listLoading: true,
        expandDefault: [],
      })
      //列表编辑
      const handleEdit = (row, type) => {
        if (row && row.PostId) {
          state['editRef'].showEdit(row, type)
        } else {
          const val = row ? row : state.queryForm
          if (!row) state['editRef'].showEdit(val, type)
        }
      }
      const renderContent = (h, node) => {
        return (
          <span class="custom-tree-node">
            <span
              style=" display: inline-block;width: 160px; overflow-x: hidden;text-overflow: ellipsis;white-space: nowrap;"
              title={node.data.text}
            >
              {node.data.text}
            </span>
          </span>
        )
      }
      //页面刷新
      const settingsStore = useSettingsStore()
      const { theme } = storeToRefs(settingsStore)
      const $pub = inject('$pub')
      const refreshRoute = () => {
        $pub('reload-router-view')
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.PostId) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await doDelete({
              companyId: row.CompanyId,
              departmentId: row.DepartmentId,
              postId: row.PostId,
            })
            //删除列表默认回到第一页
            $baseMessage(message, 'success', 'vab-hey-message-success')
            refreshRoute()
          })
        }
      }
      //菜单表格
      const fetchData = async () => {
        //wheres重新赋值
        const params = state.queryForm
        // params.wheres = `[{"name":"Code","value":"10","displayType":"equal"}]`
        params.wheres = `[{"name":"DepartmentId","value":"${params.moduleId}","displayType":"equal"}]`
        state.listLoading = true
        const {
          data: { rows, total },
        } = await getList(params)
        state.list = rows
        state.total = total
        state.listLoading = false
      }
      //树形数据点击
      const handleNodeClick = (data) => {
        //树形点击结构判断
        if (data.ChildNodes && data.ChildNodes.length > 1) {
          state.queryForm.moduleType = 'ParentId'
        } else {
          state.queryForm.moduleType = 'ModuleId'
        }
        state.queryForm.moduleId = data.id
        state.queryForm.companyId = data.CompanyId
        state.queryForm.departmentId = data.id
        fetchData()
      }
      //分页条数切换
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      //分页切换
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      //获取树形结构下第一个ID
      const getFirstNode = (tree) => {
        if (tree.ChildNodes.length > 0) {
          getFirstNode(tree.ChildNodes[0])
        } else {
          state.expandDefault.push(tree.id)
          state.queryForm.moduleId = tree.id
          state.queryForm.companyId = tree.CompanyId
          state.queryForm.departmentId = tree.id
          return
        }
      }
      //树形结构数据
      getTree(state.queryTreeForm).then(({ data }) => {
        const list = data.data
        state.data = JSON.parse(list)
        //默认选中第一个
        getFirstNode(state.data[0])
        fetchData()
      })
      // onMounted(() => {
      //   fetchData()
      // })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        Plus,
        handleCurrentChange,
        handleSizeChange,
        refreshRoute,
        MenuAuth,
        renderContent,
        translate,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.menu-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }
</style>
